<template>
  <view class="resume-container">
    <!-- 顶部信息区域 -->
    <view class="header-section">
      <view class="header-content">
        <view class="avatar-name">
          <image class="avatar" :src="avatar"></image>
          <view class="name-info">
            <view class="name-row">
              <text class="name">{{ name }}</text>
            </view>
            
            <view class="basic-info-display">
              <text class="basic-info">{{ status }} | {{ gender }} | {{ education }}</text>
            </view>
          </view>
          
          <!-- 按钮容器 -->
          <view class="btn-container">
            <!-- 编辑按钮 -->
            <view class="edit-btn" @click="toEditPage">
              <text>编辑</text>
            </view>
            
            <!-- 导出简历按钮 -->
            <view class="export-btn" @click="exportResume">
              <text>导出简历</text>
            </view>
          </view>
        </view>
        
        <!-- 联系方式区域 -->
        <view class="contact-info">
          <view class="contact-row">
            <text class="contact-label">电话：</text>
            <text class="contact-value">{{ phone }}</text>
          </view>
          <view class="contact-row">
            <text class="contact-label">邮箱：</text>
            <text class="contact-value">{{ email }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 个人优势 -->
    <view class="section">
      <text class="section-title">个人优势</text>
      <text class="content">{{ personalAdvantage }}</text>
    </view>

    <!-- 期望岗位 -->
    <view class="section">
      <text class="section-title">期望岗位</text>
      <text class="content">
        {{ desiredPosition || '未填写' }} | {{ jobRegion || '未填写' }} | 
        {{ minSalary || '未填写' }} - {{ maxSalary || '未填写' }}
      </text>
    </view>

    <!-- 教育经历 -->
    <view class="section" v-if="educationTime || educationSchoolMajor">
      <text class="section-title">教育经历</text>
      <view >
        <text class="time">时间范围:{{ educationTime }}</text>
      </view>
      <view class="">
        <text class="school-major">学校及专业：{{ educationSchoolMajor }}</text>
      </view>
      <text class="content">主修课程：{{ educationCourse }}</text>
    </view>

    <!-- 社团/组织经历 -->
    <view class="section" v-if="organizationExperience">
      <text class="section-title">社团/组织经历</text>
      <text class="content">{{ organizationExperience }}</text>
    </view>

    <!-- 专业技能及荣誉证书 -->
    <view class="section" v-if="professionalSkills">
      <text class="section-title">专业技能及荣誉证书</text>
      <text class="content">{{ professionalSkills }}</text>
    </view>

    <!-- 工作/实习经历 -->
    <view class="section"  v-if="workExperiences && workExperiences.length > 0">
      <text class="section-title">工作/实习经历</text>
      <view class="experience-item" v-for="(item, index) in workExperiences" :key="index">
        <view class="exp-header">
          <text class="experience-time">{{ item.time }}</text>
          <text class="experience-position">{{ item.position }}</text>
        </view>
        <text class="experience-content">{{ item.content }}</text>
      </view>
    </view>

    <!-- 项目经历 --> 
    <view class="section" v-if="projects && projects.length > 0">
      <text class="section-title">项目经历</text>
      <view class="project-item" v-for="(project, index) in projects" :key="index">
        <view class="project-header">
          <text class="project-time">{{ project.time }}</text>
          <text class="project-name">{{ project.name }}</text>
        </view>
        <text class="project-description">{{ project.description }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getOnlineResume,generate } from "@/api/onlineResume.js";


export default {
  data() {
    return {
	  avatar:'',
      name: '',
      status: '',
      gender: '',
      education: '',
      phone: '',
      email: '',
      personalAdvantage: '',
      jobRegion: '', 
      desiredPosition: '', 
      minSalary: '',
      maxSalary: '', 
      educationTime: '',
      educationSchoolMajor: '',
      educationCourse: '',
      organizationExperience: '',
      professionalSkills: '',
      workExperiences: [],
      projects: []
    };
  },
  onShow() {
    this.fetchResumeData();
  },
  methods: {
    formatTime(startTime, endTime) {
      return `${startTime} - ${endTime}`;
    },
    formatSchoolMajor(schoolName, major) {
      return `${schoolName} - ${major}`;
    },
    async fetchResumeData() {
      try {
        const response = await getOnlineResume();
        const data = response.data;

        this.avatar=data.avatar
        this.name = data.username || '';
        this.status = data.studyStatus  === 0
                  ? "在校生"
                  : data.studyStatus === 1
                  ? "应届毕业生"
                  : "已毕业";
        this.gender = data.sex === 1 ? '女' : data.sex === 0 ? '男' : '';
        this.education = data.education || '';
        this.phone = data.phone || '';
        this.email = data.email || '';
        this.personalAdvantage = data.introduction || '';
        this.desiredPosition = data.desiredPosition || '';
        this.jobRegion = data.jobRegion || '';
        this.minSalary = data.minSalary || '';
        this.maxSalary = data.maxSalary || '';
        this.educationTime = this.formatTime(data.eduExpsList?.[0]?.startTime, data.eduExpsList?.[0]?.endTime);
        this.educationSchoolMajor = this.formatSchoolMajor(data.eduExpsList?.[0]?.schoolName, data.eduExpsList?.[0]?.major);
        this.educationCourse = data.eduExpsList?.[0]?.mainCourse || '';
        this.organizationExperience = data.eduExpsList?.[0]?.schoolExperience || '';
        this.professionalSkills = data.professionalSkills || '';
        this.workExperiences = data.workExpsList?.map(item => ({
          time: this.formatTime(item.startTime, item.endTime),
          position: `${item.companyName} - ${item.positionName}`,
          content: item.workContent
        })) || [];
        this.projects = data.proExpsList?.map(item => ({
          time: this.formatTime(item.proStartTime, item.proEndTime),
          name: item.proName,
          description: item.proDesc
        })) || [];
      } catch (error) {
        console.error('获取简历数据失败:', error);
        uni.showToast({
          title: '获取简历数据失败',
          icon: 'none'
        });
      }
    },
    // 导出简历的方法 - 修复版
    async exportResume() {
      try {
        uni.showLoading({
          title: '正在生成简历...',
          mask: true // 一个遮罩层，为true用户无法点击页面的其他元素
        });
        
        // 修正后的数据格式，完全匹配后端RuleForm接口
        const exportData = {
          id: 0, // 简历id，导出时可以为0或从后端获取
          username: this.name || '',
          sex: this.gender === '男' ? 0 : this.gender === '女' ? 1 : 0,
          phone: this.phone || '',
          education: this.education || '',
          email: this.email || '',
          avatar: this.avatar || '',
          studyStatus: this.status === '在校生' ? 0 : this.status === '应届毕业生' ? 1 : 2,
          jobRegion: this.jobRegion || '',
          desiredPosition: this.desiredPosition || '',
          minSalary: this.minSalary || '',
          maxSalary: this.maxSalary || '',
          introduction: this.personalAdvantage || '',
          professionalSkills: this.professionalSkills || '',
          certificates: '', // 证书字段，当前没有对应数据
          
          // 教育经历 - 完全匹配后端结构
          eduExpsList: [
            {
              schoolName: this.educationSchoolMajor?.split(' - ')[0] || '',
              major: this.educationSchoolMajor?.split(' - ')[1] || '',
              education: this.education || '',
              discipline: '', // 学科字段，当前没有对应数据
              mainCourse: this.educationCourse || '',
              schoolExperience: this.organizationExperience || '',
              startTime: this.educationTime?.split(' - ')[0] || '',
              endTime: this.educationTime?.split(' - ')[1] || ''
            }
          ],
          
          // 工作经历 - 完全匹配后端结构
          workExpsList: this.workExperiences.map(item => ({
            companyName: item.position?.split(' - ')[0] || '',
            positionName: item.position?.split(' - ')[1] || '',
            department: '', // 部门字段，当前没有对应数据
            workContent: item.content || '',
            startTime: item.time?.split(' - ')[0] || '',
            endTime: item.time?.split(' - ')[1] || ''
          })),
          
          // 项目经验 - 完全匹配后端结构
          proExpsList: this.projects.map(item => ({
            proName: item.name || '',
            proRole: '', // 项目角色字段，当前没有对应数据
            proDesc: item.description || '',
            proStartTime: item.time?.split(' - ')[0] || '',
            proEndTime: item.time?.split(' - ')[1] || ''
          }))
        };

        const res = await generate(exportData);
        
        if (res.code === 200) {
          const pdfUrl = res.data || res.data.pdfUrl; // 获取pdf文件的url

          // 下载pdf
          uni.downloadFile({
            url: pdfUrl,
            success: (downloadRes) => {
              if (downloadRes.statusCode === 200) {
                // 保存文件
                uni.saveFile({
                  tempFilePath: downloadRes.tempFilePath,
                  success: (saveRes) => {
                    uni.hideLoading();
                    
                    // 显示成功提示并提供打开选项
                    uni.showModal({
                      title: '导出成功',
                      content: '简历已保存到本地，是否立即查看？',
                      confirmText: '立即查看',
                      cancelText: '稍后查看',
                      success: (modalRes) => {
                        if (modalRes.confirm) {
                          // 打开PDF文件
                          uni.openDocument({
                            filePath: saveRes.savedFilePath,
                            fileType: 'pdf',
                            success: () => {
                              console.log('成功打开PDF');
                            },
                            fail: (err) => {
                              console.error('打开PDF失败:', err);
                              uni.showToast({
                                title: '无法打开文件',
                                icon: 'none'
                              });
                            }
                          });
                        }
                      }
                    });
                  },
                  fail: (err) => {
                    uni.hideLoading();//关闭提示框的方法一般配合uni.showLoading()使用
                    console.error('保存文件失败:', err);
                    uni.showToast({
                      title: '保存失败，请重试',
                      icon: 'none'
                    });
                  }
                });
              } else {
                uni.hideLoading();
                uni.showToast({
                  title: '下载失败，请重试',
                  icon: 'none'
                });
              }
            },
            fail: (err) => {
              uni.hideLoading();
              console.error('下载失败:', err);
              uni.showToast({
                title: '网络错误，请检查网络',
                icon: 'none'
              });
            }
          });
        } else {
          uni.hideLoading();
          uni.showToast({
            title: res.message || '生成简历失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('导出简历失败:', error);
        uni.showToast({
          title: '导出失败，请重试',
          icon: 'none'
        });
      }
    },
    // 删除重复的exportResume方法
    toEditPage() {
      // 跳转到编辑页并携带当前数据
      uni.navigateTo({
        url: '/pages/mine/onlineResume/onlineResumeEdit/onlineResumeEdit'
      });
    }
  }
};
</script>

<style scoped>
.resume-container {
  padding: 40rpx;
  background-color: #f8f9fa;
  font-size: 28rpx;
  color: #333;
  min-height: 100vh;
}

.header-section {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.05);
}

.header-content {
  width: 100%;
}

.avatar-name {
  display: flex;
  align-items: flex-start;
  margin-bottom: 40rpx;
  justify-content: space-between;
}

.avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  margin-right: 30rpx;
  border: 4rpx solid #e6f7ff;
}

.name-info {
  flex: 1;
  min-width: 0;
  margin-right: 40rpx;
}

.name-row {
  width: 100%;
  margin-bottom: 30rpx;
}

.name {
  font-size: 44rpx;
  font-weight: bold;
  color: #222;
  line-height: 1.5;
}

/* 按钮容器 */
.btn-container {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

/* 编辑按钮 */
.edit-btn {
  align-self: center;
  background-color: #409eff;
  color: white;
  padding: 16rpx 32rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  cursor: pointer;
  transition: background-color 0.3s;
  white-space: nowrap;
}

/* 导出按钮 */
.export-btn {
  align-self: center;
  background-color: #67c23a;
  color: white;
  padding: 16rpx 32rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  cursor: pointer;
  transition: background-color 0.3s;
  white-space: nowrap;
}

.export-btn:active {
  background-color: #529b2e;
}

.edit-btn:active {
  background-color: #337ecc;
}

.basic-info-edit {
  width: 100%;
  font-size: 24rpx;
}

.status-row, .gender-row, .education-row {
  width: 100%;
  margin-bottom: 20rpx;
}

.status-input, .gender-input, .education-input {
  width: 100%;
  color: #666;
  font-size: 24rpx;
  padding: 16rpx 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
}

.contact-info {
  padding-left: 190rpx;
}

.contact-row {
  display: flex;
  align-items: center;
  width: 100%;
  margin-bottom: 20rpx;
}

.contact-label {
  width: 70rpx;
  flex-shrink: 0;
  color: #666;
  font-size: 24rpx;
}

.contact-value {
  line-height: 1.5;
  color: #666;
  font-size: 24rpx;
  margin-left: 10rpx;
}

.edit-input, .edit-textarea {
  padding: 16rpx 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 24rpx;
  background-color: #f9f9f9;
  box-sizing: border-box;
  line-height: 1.4;
  overflow: hidden;
  text-align: left;
}

.edit-input {
  min-height: 72rpx;
}

.name-input {
  font-size: 32rpx;
  font-weight: bold;
  width: 100%;
  max-width: calc(100% - 40rpx);
}

.contact-input {
  flex: 1;
  min-width: 0;
}

.section {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.05);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  border-left: 8rpx solid #409eff;
  padding-left: 20rpx;
  margin-bottom: 30rpx;
  display: block;
}

.content {
  line-height: 1.8;
  color: #555;
  font-size: 28rpx;
  white-space: pre-line;
}

.education-item {
  display: flex;
  justify-content: space-between;
  color: #666;
  margin-bottom: 30rpx;
  flex-wrap: wrap;
  gap: 20rpx;
}

.time, .school-major {
  line-height: 1.6;
  padding: 20rpx 0;
  font-size: 28rpx;
}

.time {
  flex: 0 0 400rpx;
}

.school-major {
  flex: 1;
}

.experience-item, .project-item {
  margin-bottom: 40rpx;
  padding-bottom: 40rpx;
  border-bottom: 2rpx dashed #f0f0f0;
}

.experience-item:last-child, .project-item:last-child {
  border-bottom: none;
}

.exp-header, .project-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
  flex-wrap: wrap;
  gap: 20rpx;
}

.experience-time, .project-time {
  color: #666;
  flex: 0 0 400rpx;
  padding: 20rpx 0;
  font-size: 28rpx;
}

.experience-position, .project-name {
  font-weight: bold;
  flex: 1;
  padding: 20rpx 0;
  font-size: 28rpx;
}

.experience-content, .project-description {
  line-height: 1.8;
  color: #555;
  font-size: 28rpx;
  white-space: pre-line;
}

.edit-textarea {
  width: 100%;
  min-height: 240rpx;
  margin-bottom: 20rpx;
}

.exp-content, .project-description {
  min-height: 200rpx;
}

.delete-btn {
  color: #f56c6c;
  font-size: 26rpx;
  text-align: right;
  margin-top: 20rpx;
  cursor: pointer;
  padding: 16rpx 0;
}

.add-btn {
  text-align: center;
  padding: 24rpx;
  border: 2rpx dashed #409eff;
  border-radius: 12rpx;
  margin-top: 30rpx;
  color: #409eff;
  font-size: 28rpx;
  cursor: pointer;
}

@media (max-width: 375px) {
  .avatar-name {
    flex-direction: column;
    gap: 30rpx;
  }
  
  .edit-btn {
    align-self: flex-start;
    margin-top: 20rpx;
  }
  
  .contact-info {
    padding-left: 0;
    margin-top: 20rpx;
  }
  
  .education-item, .exp-header, .project-header {
    flex-direction: column;
  }
  
  .time, .school-major, .experience-time, .experience-position, .project-time, .project-name {
    flex: none;
    width: 100%;
  }
  
  .time-input, .school-input, .exp-time-input, .exp-pos-input, .project-time-input, .project-name-input {
    flex: none;
    width: 100%;
  }
}

[auto-height] {
  resize: none;
  overflow: auto;
}

.edit-input:focus, .edit-textarea:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 0 4rpx rgba(64, 158, 255, 0.2);
}

.expected-position-edit {
  display: flex;
  flex-direction: column;
}

.expected-position-row {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.expected-position-row text {
  margin-right: 10rpx;
}

.edit-input {
  flex: 1;
  margin-right: 10rpx;
}
</style>